﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Modbus.Device;
using Modbus.Data;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace modbusRTU_test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            SerialPort port = new SerialPort();
            Console.WriteLine("请输入串口号(COM1，COM2……):");
            port.PortName = Console.ReadLine(); //change to your COM port
            port.DataBits = 8; //change to your data bits
            Console.WriteLine("请输入波特率(9600，19200……):");
            port.StopBits = StopBits.One; //change to your stop bits
            Console.WriteLine("请输入校验位(0=None，1=Even，2=Odd……):");
            string temp = Console.ReadLine();
            port.Parity = temp=="0"?Parity.None:temp=="1"?Parity.Even:temp=="2"?Parity.Odd:Parity.None; //change to your parity
            port.Parity = Parity.None; //change to your parity
            Console.WriteLine("请输入波特率(9600，19200……):");
            port.BaudRate =Convert.ToInt32(Console.ReadLine()); //change to your baud rate
            port.Open();

            ModbusSerialMaster modbusSerialMaster = ModbusSerialMaster.CreateRtu(port);
            byte slaveId = 1;
            ushort[] ret;
            while(slaveId < 253)
            {
                try
                {
                    ret = modbusSerialMaster.ReadHoldingRegisters(slaveId, 0, 1);
                }
                catch(Exception e)
                {
                    Console.WriteLine(e.ToString());
                    continue;
                }
                if (ret[0] == 486)
                {
                    Console.WriteLine("slaveId:{0} is ok", slaveId);
                    break;
                }
                Console.WriteLine("slaveId:{0} is not ok", slaveId);
                slaveId++;
            }
            port.Close();
        }
    }
}
